package com.haiyou.dc.thread.test1;

/**
 * 线程不安全：取钱：数据不一致
 * 账号100元，
 * 1、你和妻子同时去取，都取到100元
 * 2、你往账户存100，妻子同时取100，你发现账号余额还是100
 */
public class UnsafeTest02 {

    public static void main(String[] args) {
        Account account = new Account(100, "结婚礼金");

        Drawing you = new Drawing(account, 80, "伤心的你");
        Drawing wife = new Drawing(account, 90, "开心的她");
        you.start();
        wife.start();
    }

}

/**
 * 账号
 */

class Account {
    public int money;
    public String name;

    public Account(int money, String name) {
        this.money = money;
        this.name = name;
    }
}

class Drawing extends Thread {

    private int drawMoney;
    private int packetMoney;
    private Account account;

    public Drawing(Account account, int drawMoney, String name) {
        super(name);
        this.account = account;
        this.drawMoney = drawMoney;
    }

    @Override
    public void run() {

        if (account.money - this.drawMoney < 0) {
            return;
        }

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        account.money -= this.drawMoney;
        this.packetMoney += this.drawMoney;

        System.out.println(this.getName() + "--->账号余额=" + account.money);
        System.out.println(this.getName() + "--->口袋余额=" + this.packetMoney);

    }
}